from django.db import models
import requests
from lxml import etree
# Create your models here.
path = '/html/body/div[1]/div/section[2]/div[1]/div[1]/div/div/div/div[1]/div/div[2]/p/span'


class Address(models.Model):
    address = models.CharField(max_length=50, unique=True)
    is_enable = models.BooleanField(default=True)

    def __str__(self):
        return self.address

    def get_cookie(self):
        url = f'https://firsttron.com/en/member-login/{self.address}'
        page = requests.get(url)
        if page.status_code == 200:
            return page.cookies
        else:
            return None

    def get_trx(self):
        cookies = self.get_cookie()
        value = None
        if cookies:
            page = requests.get('https://firsttron.com/en/home', cookies=cookies)
            selector = etree.HTML(page.content)
            span = selector.xpath(path)
            if span:
                value = span[0].text.split('TRX ')[1]
        print(self.address, value)
        return value

    def set_or_update_value(self):
        obj, created = TRXValue.objects.update_or_create(address=self, defaults={
            "withdraw_wallet": self.get_trx()
        })


class TRXValue(models.Model):
    address = models.OneToOneField(Address, on_delete=models.PROTECT)
    withdraw_wallet = models.FloatField(default=0)

